package com.xhsj.user.hr.process.hrTransferJob.service;

import com.xhsj.user.hr.process.dto.hrTransferJob.MyTransferJobApplyListDto;
import com.xhsj.user.hr.process.dto.hrTransferJob.RunTransferJobApplyListDto;
import com.xhsj.user.hr.process.dto.hrTransferJob.ReturnTransferJobApplyDto;
import com.xhsj.user.hr.process.dto.processDefinition.HandleAuditDto;
import com.xhsj.user.hr.process.hrBecomeRegular.service.TbHrApprovalBecomeRegularApplyService;
import com.xhsj.user.hr.process.hrLeaveProcess.mapper.TbHrApprovalLeaveApplyMapper;
import com.xhsj.user.hr.process.hrLeaveProcess.query.ApprovalHiTaskQuery;
import com.xhsj.user.hr.process.hrLeaveProcess.query.WorkFlowNodeQuery;
import com.xhsj.user.hr.process.hrTransferJob.entity.TbHrApprovalTransferJob;
import com.xhsj.user.hr.process.hrTransferJob.mapper.TbHrApprovalTransferJobMapper;
import com.xhsj.user.hr.process.hrTransferJob.query.*;
import com.xhsj.user.hr.base.BaseService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhsj.user.hr.process.processDefinition.query.ProcessNodeQuery;
import com.xhsj.user.hr.process.processDefinition.service.TbGlobalApprovalHiTaskService;
import com.xhsj.user.hr.process.processDefinition.service.TbGlobalApprovalTaskService;
import com.xhsj.user.hr.process.processDefinition.service.TbGlobalWorkFlowNodeService;
import com.xhsj.user.hr.process.query.ApprovalQuery;
import com.xhsj.user.security.entity.LoginUser;
import com.xhsj.user.hr.system.entity.TbGlobalUser;
import com.xhsj.user.hr.system.mapper.TbGlobalRoleMapper;
import com.xhsj.user.hr.system.service.TbGlobalUserService;
import com.xhsj.user.utils.MessageConstant;
import com.xhsj.user.utils.UserUtils;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;
/**
 * <p>
 * hr流程_调岗申请 服务实现类
 * </p>
 *
 * @author liuqinghua
 * @since Sep 14, 2020 10:52:15 AM
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
//@CacheConfig(cacheNames = "TbHrApprovalTransferJob")
public class TbHrApprovalTransferJobService extends BaseService<TbHrApprovalTransferJobMapper, TbHrApprovalTransferJob>{
    @Autowired
    private TbHrApprovalTransferJobMapper dao;

    // 角色信息表 Mapper 接口
    @Autowired
    private TbGlobalRoleMapper tbGlobalRoleMapper;

    // 流程-历史表 服务实现类
    @Autowired
    private TbGlobalApprovalHiTaskService tbGlobalApprovalHiTaskService;

    // 流程设计-流程节点 服务实现类
    @Autowired
    private TbGlobalWorkFlowNodeService tbGlobalWorkFlowNodeService;

    // 流程-任务审核表 服务实现类
    @Autowired
    private TbGlobalApprovalTaskService tbGlobalApprovalTaskService;

    // 用户信息表 服务实现类
    @Autowired
    private TbGlobalUserService tbGlobalUserService;

    @Autowired
    private TbHrApprovalBecomeRegularApplyService tbHrApprovalBecomeRegularApplyService;

    @Autowired
    private TbHrApprovalLeaveApplyMapper tbHrApprovalLeaveApplyMapper;


	/**
	 * 保存
	 * @author liuqinghua
	 * @date Sep 14, 2020 10:52:15 AM
	 */
    @Override
    //@CacheEvict(cacheNames="TbHrApprovalTransferJob", allEntries=true)
    public boolean save(TbHrApprovalTransferJob entity) {
        return super.save(entity);
    }

	/**
	 * 通过id获取数据
	 * @author liuqinghua
	 * @date Sep 14, 2020 10:52:15 AM
	 */
    @Override
    //@Cacheable(key = "#id",sync = true)
    public TbHrApprovalTransferJob getById(Serializable id) {
        return super.getById(id);
    }

	/**
	 * 通过id删除数据
	 * @author liuqinghua
	 * @date Sep 14, 2020 10:52:15 AM
	 */
    @Override
    //@CacheEvict(cacheNames="TbHrApprovalTransferJob", allEntries=true)
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

	/**
	 * 批量删除数据
	 * @author liuqinghua
	 * @date Sep 14, 2020 10:52:15 AM
	 */
    //@CacheEvict(cacheNames="SysDict", allEntries=true)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
    }

	/**
	 * 分页查询数据
	 * @author liuqinghua
	 * @date Sep 14, 2020 10:52:15 AM
	 */
    //@Cacheable(key = "#data",sync = true)
    public IPage<TbHrApprovalTransferJob> selectPage(Map<String,Object> data) {
        int currentPage=1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage=(Integer) data.get("page");
        }
        int pageSize=20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize=(Integer) data.get("size");
        }

        TbHrApprovalTransferJob entity = JSON.parseObject(JSON.toJSONString(data), TbHrApprovalTransferJob.class);
        Page<TbHrApprovalTransferJob> page = new Page(currentPage,pageSize);
        QueryWrapper<TbHrApprovalTransferJob> wrapper = new QueryWrapper(entity);
        return super.selectPage(page, wrapper);
    }

	/**
	 * 查询所有数据
	 * @author liuqinghua
	 * @date Sep 14, 2020 10:52:15 AM
	 */
    @Override
    //@Cacheable(value = "TbHrApprovalTransferJob",sync = true)
    public List<TbHrApprovalTransferJob> selectAll() {
        return super.selectAll();
    }


    /**
     * 我的调职申请列表
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public IPage<MyTransferJobApplyListQuery> myTransferJobApplyList(MyTransferJobApplyListDto data) {
        LoginUser loginAppUser = UserUtils.getLoginAppUser();
        Long userId = loginAppUser.getUserId();
        Page<MyTransferJobApplyListQuery> page = new Page<>(data.getPage(),data.getSize());
        return dao.myTransferJobApplyList(page,userId,data);
    }

    /**
     * 待审核调岗申请列表
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public IPage<RunTransferJobApplyListQuery> runTransferJobApplyList(RunTransferJobApplyListDto data) {
        Page<RunTransferJobApplyListQuery> page = new Page<>(data.getPage(),data.getSize());
        LoginUser loginAppUser = UserUtils.getLoginAppUser();
        Long userId = loginAppUser.getUserId();
        // 获取用户角色id
        List<Long> roleList = tbGlobalRoleMapper.getRoleListByUserId(userId);
        return dao.runTransferJobApplyList(page,userId,roleList,data);
    }

    /**
     * 已审核调岗申请列表
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public IPage<CompletedTransferJobApplyQuery> completedTransferJobApplyList(RunTransferJobApplyListDto data) {
        Page<CompletedTransferJobApplyQuery> page = new Page<>(data.getPage(),data.getSize());
        LoginUser loginAppUser = UserUtils.getLoginAppUser();
        Long userId = loginAppUser.getUserId();
        return dao.completedTransferJobApplyList(page,userId,data);
    }

    /**
     * 我的调岗申请详细信息
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public MyTransferJobApplyDetailedListQuery myTransferJobApplyDetailedList(Long dataId) {
        MyTransferJobApplyDetailedListQuery myTransferJobApplyDetailedListQuery= new MyTransferJobApplyDetailedListQuery();
        // 调薪申请基本信息
        TransferJobApplyBaseDetailedQuery apply = dao.transferJobApplyBaseDetailedList(dataId);
        if (apply != null) {
            Long businessId = apply.getBusinessId();
            myTransferJobApplyDetailedListQuery.setApply(apply);
            // 审批意见
            List<ApprovalHiTaskQuery> approvalHiTaskList = tbGlobalApprovalHiTaskService.getApprovalHiTaskList(dataId, businessId);
            myTransferJobApplyDetailedListQuery.setCommentList(approvalHiTaskList);

            // 流程节点
            List<WorkFlowNodeQuery> workFlowNodeQueries = tbGlobalWorkFlowNodeService.nodeList(businessId);
            myTransferJobApplyDetailedListQuery.setNodeList(workFlowNodeQueries);
        }
        return myTransferJobApplyDetailedListQuery;
    }

    /**
     * hr流程-调岗申请开始
     * @author liuqinghua
     * @date Sep 7, 2020 10:42:13 AM
     */
    public ApprovalQuery startTransferJobApply(TbHrApprovalTransferJob data) throws Exception {
        // 保存申请数据
        if (!super.save(data)) {
            throw new Exception("保存调岗申请信息异常");
        }
        // 执行流程
       return this.startTransferJobApplyRun(data);
    }

    /**
     * 执行开始调岗流程启动
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public ApprovalQuery startTransferJobApplyRun(TbHrApprovalTransferJob apply) throws Exception {
        HandleAuditDto handleAuditDto = new HandleAuditDto();
        handleAuditDto.setDataId(apply.getId());
        handleAuditDto.setProposerId(apply.getCreateBy());
        handleAuditDto.setCreateBy(apply.getCreateBy());
        handleAuditDto.setApplyType(5);
        // 执行流程
        ProcessNodeQuery processNodeQuery = tbGlobalApprovalTaskService.startHandleAudit(handleAuditDto,apply.getOldDepartmentId());
        // 修改调岗申请表节点名称和节点id
       return this.updateHrApprovalTransferJobApply(handleAuditDto,processNodeQuery,UserUtils.getLoginAppUser().getFullName());
    }

    // 修改节点id和节点名称调岗申请
    public ApprovalQuery updateHrApprovalTransferJobApply(HandleAuditDto data,ProcessNodeQuery processNodeQuery,String fullName) throws Exception {
        //修改调岗申请表节点名称和节点id
        TbHrApprovalTransferJob tbHrApprovalTransferJob = new TbHrApprovalTransferJob();
        tbHrApprovalTransferJob.setId(data.getDataId());
        tbHrApprovalTransferJob.setNodeName(processNodeQuery.getNodeName());
        tbHrApprovalTransferJob.setNodeId(processNodeQuery.getNodeId());
        tbHrApprovalTransferJob.setBusinessId(data.getBusinessId());
        tbHrApprovalTransferJob.setDelFlag(processNodeQuery.getDelFlag());
        if (!this.save(tbHrApprovalTransferJob)) {
            throw new Exception("修改调岗申请节点名称信息异常");
        }
        // 消息参数
        return tbHrApprovalBecomeRegularApplyService.setApprovalQuery(data.getDataId(),
                4,
                MessageConstant.MSG_10,
                processNodeQuery,
                fullName);
    }

    /**
     * 调岗流程审批
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public ApprovalQuery approvalTransferJobApply(HandleAuditDto data) throws Exception {
        // 执行流程
        ProcessNodeQuery processNodeVo = tbGlobalApprovalTaskService.handleAudit(data);
        String fullName = tbHrApprovalLeaveApplyMapper.getFullNameByDataId(data.getDataId(),"tb_hr_approval_transfer_job");
        // 修改产品申请表节点名称和节点id
        ApprovalQuery approvalQuery = updateHrApprovalTransferJobApply(data, processNodeVo,fullName);
        if ("完结".equals(processNodeVo.getNodeName())) {
            // 当前时间
            Date day = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String format = df.format(day);
            long time = df.parse(format).getTime();
            // 获取调整后岗位和职位
            TbHrApprovalTransferJob tbHrApprovalTransferJob = dao.selectById(data.getDataId());
            if (time == tbHrApprovalTransferJob.getEffectiveDate().getTime()) {
            Long userId = tbHrApprovalTransferJob.getUserId();
            // 修改岗位和职位
            TbGlobalUser tbGlobalUser = new TbGlobalUser();
            tbGlobalUser.setUserId(userId);
            tbGlobalUser.setPositionId(tbHrApprovalTransferJob.getNewPositionId());
            tbGlobalUser.setDepartmentId(tbHrApprovalTransferJob.getNewDepartmentId());
            tbGlobalUser.setLeader(tbHrApprovalTransferJob.getNewLeaderId());
            if (!tbGlobalUserService.updateById(tbGlobalUser)) {
                throw new Exception("修改岗位和职位异常");
            }
            }
        }
        return approvalQuery;
    }

    /**
     * 调岗定时器 定期生效
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public void approvalTransferJobEffective() throws Exception {
        Date day = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String format = df.format(day);
        // 获取今天将生效的调岗
        QueryWrapper<TbHrApprovalTransferJob> queryWrapper = new QueryWrapper();
        queryWrapper.eq("effective_date",format);
        queryWrapper.eq("node_name","完结");
        List<TbHrApprovalTransferJob> tbHrApprovalTransferJobs = dao.selectList(queryWrapper);
        for (TbHrApprovalTransferJob tbHrApprovalTransferJob : tbHrApprovalTransferJobs) {
            Long userId = tbHrApprovalTransferJob.getUserId();
            // 修改岗位和职位
            TbGlobalUser tbGlobalUser = new TbGlobalUser();
            tbGlobalUser.setUserId(userId);
            tbGlobalUser.setPositionId(tbHrApprovalTransferJob.getNewPositionId());
            tbGlobalUser.setDepartmentId(tbHrApprovalTransferJob.getNewDepartmentId());
            tbGlobalUser.setLeader(tbHrApprovalTransferJob.getNewLeaderId());
            if (!tbGlobalUserService.updateById(tbGlobalUser)) {
                throw new Exception("修改岗位和职位异常");
            }
        }

    }


    /**
     *  调岗申请重新提交
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public ApprovalQuery returnTransferJobApply(ReturnTransferJobApplyDto data) throws Exception {
        // 修改申请数据
        TbHrApprovalTransferJob apply = data.getApply();
        if (!super.save(apply)) {
            throw new Exception("修改申请数据异常");
        }
        // 执行流程
        HandleAuditDto handleAudit = data.getHandleAuditDto();
        handleAudit.setStatus(0);
        return this.approvalTransferJobApply(handleAudit);
    }

    /**
     * 调岗申请删除
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public boolean deleteTransferJobApply(Long dataId) throws Exception {
        int i = dao.deleteTransferJobApply(dataId);
        if (i == 0) {
           throw new Exception("调岗申请删除异常");
        }
        return true;
    }

    /**
     * 调岗流程作废
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public ApprovalQuery approvalTransferJobToVoidApply(HandleAuditDto data) throws Exception {
        // 执行流程
        data.setNodeId(-11L);
        ProcessNodeQuery processNodeVo = tbGlobalApprovalTaskService.handleAudit(data);
        // 修改产品申请表节点名称和节点id
       return updateHrApprovalTransferJobApply(data, processNodeVo,"");
    }
}
